package cn.com.citydo.base.intercepter;

import cn.com.citydo.base.anotation.ResponseResultAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import static cn.com.citydo.base.constant.ResponseResultConstant.RESPONSE_RESULT_ANN;

/**
 * Create By Cuixk
 * 2019/7/3 11:30
 */
@Slf4j
@Component
public class ResponseResultIntercepter implements HandlerInterceptor {

    /**
     * 此代码核心 ，即是获取此请求 ，判断是否需要返回值包装，为此设置一个属性标记
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(ResponseResultAnnotation.class) || method.isAnnotationPresent(ResponseResultAnnotation.class)) {
                request.setAttribute(RESPONSE_RESULT_ANN,clazz.getAnnotation(ResponseResultAnnotation.class));
            }
        }

        return true;
    }
}
